<template>
  <div>
    <el-card shadow="never" class="margin-30">
      <el-form :model="form" label-width="80px" size="min">
        <el-row :gutter="20">
          <el-col :span="6" :offset="0">
            <el-form-item label="昵称" size="mini">
              <el-input v-model="form.nickName" placeholder="昵称模糊搜索" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="用户名" size="mini">
              <el-input v-model="form.username" placeholder="用户名模糊搜索" size="mini" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="end" :gutter="20">
          <el-col :span="4" :offset="0">
            <el-button size="mini" @click="resetSearchForm">重置</el-button>
            <el-button type="primary" size="mini" @click="searchAccount">查询</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="never" class="margin-30">
      <div slot="header">
        <el-button type="primary" size="mini" @click="openModal('')">新增</el-button>
      </div>
      <el-table :data="accountList" border stripe>
        <el-table-column
          type="index"
          label="序号"
        />
        <el-table-column
          prop="username"
          label="用户名"
        />
        <el-table-column
          prop="nick_name"
          label="昵称"
        />
        <el-table-column
          label="头像"
        >
          <template slot-scope="scope">
            <img width="120" height="80" :src="scope.row.salt" alt="">
          </template>
        </el-table-column>
        <el-table-column
          prop="roles"
          label="角色"
        />
        <el-table-column
          prop="create_time"
          label="添加时间"
        />
        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">
            <el-button type="success" size="mini" @click="openModal(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="mini" @click="deleteAccount(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        align="right"
        style="margin-top:10px;"
        :current-page="pagination.start"
        :page-sizes="pagination.sizes"
        :page-size="pagination.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog
      title="编辑用户"
      :visible.sync="accountVisible"
      width="40%"
      @close="closeModal"
    >
      <el-form ref="form" :model="editFrom" :rules="rules" label-width="80px" size="mini">
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="用户名" size="small" prop="username">
              <el-input v-model="editFrom.username" class="width-100" placeholder="用户名" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="用户昵称" size="small" prop="nickName">
              <el-input v-model="editFrom.nickName" class="width-100" placeholder="用户昵称" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="id===''" :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="密码" size="small">
              <el-input v-model="editFrom.password" placeholder="密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="用户头像" size="small">
              <el-upload
                ref="uploadImg"
                class="avatar-uploader"
                :action="uploadImageUrl"
                :headers="token"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeCoverImgUpload"
              >
                <img v-if="editFrom.salt" :src="editFrom.salt" class="avatar">
                <i v-else class="iconfont  icon-touxiang avatar" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="选择角色" size="small" prop="roleIds">
              <el-select v-model="editFrom.roleIds" multiple placeholder="选择角色" clearable>
                <el-option
                  v-for="item in roleIds"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                />
              </el-select>

            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer">
        <el-button @click="accountVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  findUsersByPage as findUsersByPageApi,
  removeUser as removeUserApi,
  findAllRoles as findAllRolesApi,
  saveUserRoles as saveUserRolesApi,
  updateUserRoles as updateUserRolesApi,
  user as userApi
} from '@/api/auth/account'
import mix from '@/mixin'
export default {
  name: 'Account',
  mixins: [mix],
  data() {
    return {
      accountList: [],
      form: {},
      accountVisible: false,
      editFrom: {
        salt: '',
        password: ''
      },
      rules: {
        username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
        nickName: [{ required: true, trigger: 'blur', message: '请输入用户昵称' }],
        roleIds: [{ type: 'array', required: true, trigger: 'blur', min: 1, message: '请选择角色' }]
      },
      roleIds: [],
      id: ''
    }
  },
  created() {
    this.getAccountList()
    this.getAllRoles()
  },
  methods: {
    getSingleAccount() {
      userApi(this.id)
        .then(res => {
          const { message, success, data } = res
          if (success) {
            this.editFrom = data.user
          } else {
            this.$message.error(message)
          }
        })
    },
    // 获取所有角色列表
    getAllRoles() {
      findAllRolesApi()
        .then(res => {
          const { message, data, success } = res
          if (success) {
            this.roleIds = data.items
          } else {
            this.$message.error(message)
          }
        })
    },
    // 文件上传成功时候的钩子函数
    handleAvatarSuccess(res, file, fileList) {
      const { success, message, data } = res
      if (success) {
        this.editFrom.salt = data.fileUrl
        this.$refs.uploadImg.clearFiles()
      } else {
        this.$message.error(message)
      }
    },
    // 在文件上传之前的钩子函数
    beforeCoverImgUpload(file) {
      const isLt1dot5M = file.size / 1024 / 1024 < 1.5
      var reg = /^image\/(jpe?g|png|webp|gif)$/

      const isImage = reg.test(file.type)
      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt1dot5M) {
        this.$message.error('上传头像图片大小不能超过 1.5MB!')
      }
      return isImage && isLt1dot5M
    },
    // 打开模态框
    openModal(id) {
      this.accountVisible = true
      this.id = id
      if (id) {
        this.getSingleAccount()
      }
    },
    // 关闭模态框
    closeModal() {
      this.accountVisible = false
      this.editFrom = this.$options.data().form
    },
    // 保存
    save() {
      this.$refs.form.validate((valid, error) => {
        if (valid) { // 验证通过
          var api = null
          var mes = ''
          if (this.id) { // 更新账号
            api = updateUserRolesApi
            mes = '更新'
          } else { // 新增账号
            api = saveUserRolesApi
            mes = '新增'
          }
          api(this.editFrom)
            .then(res => {
              const { message, success } = res
              if (success) {
                this.$message.success(mes + '账号成功!')
                this.getAccountList()
                this.accountVisible = false
              } else {
                this.$message.error(message)
              }
            })
        } else { // 验证失败
          for (var key in error) {
            if (error[key]) {
              const message = error[key][0].message
              this.$message.error(message)
            }
          }
        }
      })
    },
    // 搜索
    searchAccount() {
      this.pagination.start = 1
      this.getAccountList()
    },
    // 重置搜索表单
    resetSearchForm() {
      this.form = {}
      this.pagination.start = 1
      this.getAccountList()
    },
    // 改变limit一页多少条数据
    handleSizeChange(e) {
      this.pagination.limit = e
      this.pagination.start = 1
      this.getAccountList()
    },
    // 改变当前页数start
    handleCurrentChange(e) {
      this.pagination.start = e
      this.getAccountList()
    },
    // 删除用户账户
    deleteAccount(id) {
      this.$confirm('确认删除', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'none'
      }).then(() => {
        removeUserApi(id)
          .then(res => {
            const { message, success } = res
            if (success) {
              this.$message.success('删除用户账号成功!')
              this.getAccountList()
            } else {
              this.$message.error(message)
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取用户账号高列表
    getAccountList() {
      this.filterNullParamsObject(this.form)
      var data = null
      this.loading = true
      if (this.passForm) {
        // data = [this.pagination.start, this.pagination.limit, this.form]
        data = [this.pagination.start, this.pagination.limit, this.form]
      } else {
        data = [this.pagination.start, this.pagination.limit]
      }
      findUsersByPageApi(...data)
        .then(res => {
          const { message, success, data } = res
          if (success) {
            this.accountList = data.rows
            this.pagination.total = data.total
          } else {
            this.$message.error(message)
          }
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.width-100{
  width:100%;
}
label{
  font-weight: 700;
}
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
  .avatar {
    width: 40px;
    height: 40px;
    display: block;
    font-size: 40px;
    border-radius: 50%;
  }
</style>
